#include <iostream>
#include <opencv2/opencv.hpp>


using cv::Mat;
using std::max;
using std::min;

// 以短边为size=224基准,按照长短边比例进行缩放，随后有224为短边的长方形，取中间224x224区域；长短边一致时为特殊情况。
cv::Mat CenterCrop(cv::Mat img, cv::Rect rect, int size = 224) {
    int minX = rect.x;
    int minY = rect.y;
    int bbox_height = rect.height;
    int bbox_width = rect.width;
    int maxX = minX + bbox_width;
    int maxY = minY + bbox_height;
    minX = max(minX, 0);
    minY = max(minY, 0);
    maxX = min(img.size[1], maxX);
    maxY = min(img.size[0], maxY);
    int w = maxX - minX;
    int h = maxY - minY;
    cv::Mat cropImg_0 = img(CvRect(minX, minY, w, h));
    int ow = size, oh = size;
    if (w > h)
        ow = size * w / h;
    else if (w < h)
        oh = size * h / w;

    cv::resize(cropImg_0, cropImg_0, cv::Size(ow, oh), cv::INTER_LINEAR);

    int oj = (ow - size) / 2;
    int oi = (oh - size) / 2;
    cv::Mat cropImg_ = cropImg_0(CvRect(oj, oi, size, size));
    return cropImg_;
}

int main() {


    cv::Mat im = cv::imread("../0066_02_1.jpg");

    cv::Rect rect;
    rect.x = 72;
    rect.y = 40;
    rect.height = 350;
    rect.width = 350;
    cv::Mat crop_face = CenterCrop(im, rect);
    cv::rectangle(im,rect,cv::Scalar(255,255,0),2);
    std::cout << "width: " << crop_face.cols << "height:" << crop_face.rows << std::endl;


    cv::Rect rect2;
    rect2.x = 175;
    rect2.y = 200;
    rect2.height = 30;
    rect2.width = 60;
    cv::Mat crop_eye = CenterCrop(im, rect2);
    cv::rectangle(im,rect2,cv::Scalar(255,255,0),2);
    std::cout << "width: " << crop_eye.cols << "height:" << crop_eye.rows << std::endl;


    cv::Rect rect3;
    rect3.x = 342;
    rect3.y = 233;
    rect3.height = 100;
    rect3.width = 60;
    cv::Mat crop_ear = CenterCrop(im, rect3);
    cv::rectangle(im,rect3,cv::Scalar(255,255,0),2);
    std::cout << "width: " << crop_ear.cols << "height:" << crop_ear.rows << std::endl;


    cv::imshow("window",im);
    cv::imshow("window2",crop_face);
    cv::imshow("window3",crop_eye);
    cv::imshow("window4",crop_ear);
    cv::waitKey(0);

    return 0;
}